package controller;

import android.content.Context;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.HashMap;
import java.util.Map;

import common.ISendData;
import model.RequestModel;
import utils.HttpRequestUtils;
import utils.KeyCode;

/**
 * Created by Admin on 2016/3/14.
 */
public class UserLoginController {

    private static final String userUrl = "https://eshop.yuanguozheng.com/users/%s";
    private HttpRequestUtils reqRegister;
    private Context mContext;
    private HttpRequestUtils loginReq;

    public UserLoginController(Context context) {
        mContext = context;
        if (null == loginReq) {
            loginReq = new HttpRequestUtils(context);
        }
    }

    //登录
    public void userLogin() {
        if (null == loginReq) {
            loginReq = new HttpRequestUtils(mContext);
        }


    }

    //退出登录
    public void userLogout() {

    }

    //注册
    public void register(String phone, String pwd, String email, String name, final ISendData iSendData) {

        if (null == reqRegister) {
            reqRegister = new HttpRequestUtils(mContext);
        }
        String key = "a47151ce23553fbeeb52c6accf485414be4f3071";
        String timestamp = System.currentTimeMillis() + "";
        String sign = timestamp + "email=" + email + "&nickName=" + name  + "&phone=" + phone+ "&password=" + pwd + key;
        Map<String, String> map = new HashMap<>();
        Map<String, String> headers = new HashMap<>();
        headers.put("timestamp", timestamp);
        map.put("phone", phone);
        //使用MD5加密密码
        //  String password = KeyCode.getMd5Value(pwd);
        String password = pwd;
        map.put("password", password);
        map.put("email", email);
        map.put("nickName", name);
        map.put("sign", KeyCode.getSHAValue(sign));
        reqRegister.postRequestString(String.format(userUrl, "register"), map, headers, new ISendData() {
            @Override
            public void sendData(Object o) {
                handleRegister(iSendData, o);
            }
        });

    }

    private void handleRegister(ISendData iSendData, Object o) {
        try {
            String info = (String) o;
            Gson gson = new Gson();
            RequestModel<Object> reqData = gson.fromJson(info, new TypeToken<RequestModel<Object>>() {
            }.getType());
            iSendData.sendData(reqData);
        } catch (Exception e) {

        }
    }
}
